package com.dhecp.project.storage.service.impl;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.FbaProductActive;
import com.dhecp.project.business.domain.ProductActive;
import com.dhecp.project.business.mapper.ProductActiveMapper;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.mapper.ModuleNidAndBidMapper;
import com.dhecp.project.common.service.UpdateLogService;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.flowable.mapper.SysProcessInstanceMapper;
import com.dhecp.project.flowable.service.ActProcessService;
import com.dhecp.project.storage.domain.DeliveryBox;
import com.dhecp.project.storage.domain.DeliveryBoxDetail;
import com.dhecp.project.storage.domain.DeliveryRequest;
import com.dhecp.project.storage.domain.DeliveryRequestDetail;
import com.dhecp.project.storage.domain.StockControl;
import com.dhecp.project.storage.domain.StockControlRunning;
import com.dhecp.project.storage.enums.DeliveryBoxEnum;
import com.dhecp.project.storage.enums.DeliveryRequestEnum;
import com.dhecp.project.storage.mapper.DeliveryBoxDetailMapper;
import com.dhecp.project.storage.mapper.DeliveryBoxMapper;
import com.dhecp.project.storage.mapper.DeliveryRequestDetailMapper;
import com.dhecp.project.storage.mapper.DeliveryRequestMapper;
import com.dhecp.project.storage.mapper.StockControlMapper;
import com.dhecp.project.storage.mapper.StockControlRunningMapper;
import com.dhecp.project.storage.service.DeliveryRequestService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 查询海外发货申请单 服务层
 */
@Service
public class DeliveryRequestServicelmpl extends BaseModuleServiceImpl implements DeliveryRequestService {

    private String moduleTable1 = ModuleTable.DELIVERY_REQUEST_DETAIL;

    @Autowired
    private DeliveryRequestMapper deliveryRequestMapper;
    @Autowired
    private DeliveryBoxMapper deliveryBoxMapper;
    @Autowired
    private DeliveryBoxDetailMapper deliveryBoxDetailMapper;

    @Autowired
    private DeliveryRequestDetailMapper deliveryRequestDetailMapper;
    @Autowired
    private ProductActiveMapper productActiveMapper;

    @Autowired
    private StockControlMapper stockControlMapper;

    @Autowired
    private StockControlRunningMapper stockControlRunningMapper;

    @Autowired
    private UpdateLogService updateLogService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private ActProcessService actProcessService;
    

    @Autowired
    private SysProcessInstanceMapper sysProcessInstanceMapper;

    @Autowired
    private ModuleNidAndBidMapper moduleNidAndBidMapper;

    /**
     * 查询查询海外发货申请单
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<DeliveryRequest> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句

        if (params.get("field") == null || params.get("field") == ""){
            String orderBy = "t1.createTime DESC";
            PageUtils.startPageOrder(orderBy);
        }else{
            PageUtils.startPage();
        }
        return deliveryRequestMapper.select(params);
    }

    /**
     * 查询海外发货申请单-明细
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<DeliveryRequestDetail> querySonListByBid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        String orderBy = "t1.createTime DESC";
        PageUtils.startPageOrder(orderBy);
        return deliveryRequestMapper.querySonListByBid(params);
    }
    /**
     * 查询查询海外发货申请单
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public DeliveryRequest queryFirstRecord(Map<String, Object> params) throws Exception {

        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return deliveryRequestMapper.selectFirstRecordByNid(params);
    }

    /**
     * 查询海外发货申请单-明细
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<DeliveryRequestDetail> queryDetailListByBid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        String orderBy = "t1.commodityCode ASC";
        PageUtils.startPageOrder(orderBy);
        List<DeliveryRequestDetail> detailList = deliveryRequestMapper.querySonListByBid(params);

        return detailList;
    }


    /**
     * 查询箱规维护
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<DeliveryRequestDetail> selectGuageByStore(Map<String, Object> params) throws Exception {
        List<DeliveryRequestDetail>  list = deliveryRequestMapper.selectGuageByStore(params);
        return list;
    }

    /**
     * 查询库存编码
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<FbaProductActive> findFbaProductByDeliveryRequestDetail(Map<String, Object> params) throws Exception {
        List<FbaProductActive>  list = deliveryRequestMapper.findFbaProductByDeliveryRequestDetail(params);
        return list;
    }



    @SuppressWarnings("unchecked")
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new DeliveryRequest());

        String guidFind = JSON.parseObject(params.get("infoMap").toString()).getString("guid");
        DeliveryRequest deliveryRequest2 = null;
        if (guidFind != null && !guidFind.equals("")){
            deliveryRequest2 = deliveryRequestMapper.queryFirstByGuid(guidFind);
            if (deliveryRequest2 == null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("海外仓发货申请不存在,请核实后在操作!");
            }
        }

        AjaxResult ajaxResult = this.saveDataBase(params);

        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        String resNid = infoMap.get("nid").toString();

        DeliveryRequest deliveryRequest = JSON.parseObject(params.get("infoMap").toString(), DeliveryRequest.class);
        List<DeliveryRequestDetail> onSonData = JSON.parseArray(params.get("infoItems").toString(), DeliveryRequestDetail.class);

        //if (params.containsKey("sonData")){
            //onSonData =
        //}

        List<RecordCheck> guidMapList = deliveryRequestMapper.findRecords(resNid);

        Map<String, Object> guidMap = new HashMap<String, Object>();

        if (!guidMapList.isEmpty()){
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())){ //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList){
                if (recordCheck != null && recordCheck.getGuid() != null){
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }


        if (onSonData == null || onSonData.size() == 0){
            resNid = "0";
        }else{
            resNid = infoMap.get("nid").toString();
            String guid = "";
            if (deliveryRequest.getGuid() == null){
                guid = RandomValueUtils.getGUID();
                deliveryRequest.setGuid(guid);
            }else{
                guid = deliveryRequest.getGuid().toString();
            }

            for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                Object fieldValue = infoMap.get(field);
                ReflectUtils.setValue(deliveryRequest, field, fieldValue);
            }

            if (guidMap.get(guid) == null){
                //deliveryRequest.setCode(deliveryRequest.getBid());
                deliveryRequest.setDeleted(false);
                //deliveryRequest.setCreateUser(ShiroUtils.getMandatorId());
                deliveryRequest.setStateName(DeliveryRequestEnum.StateName.INIT.value);
                deliveryRequestMapper.inserDeliveryRequest(deliveryRequest);
            }else{
                deliveryRequest.setStateName(DeliveryRequestEnum.StateName.INIT.value);
                deliveryRequestMapper.updateByGuid(deliveryRequest);
                guidMap.remove(guid);
            }


            List<DeliveryRequestDetail> lodData = deliveryRequestDetailMapper.queryFirstByPBid(deliveryRequest.getBid());


            for (DeliveryRequestDetail item : onSonData
            ) {
                if (item.getGuid() != null && !item.getGuid().equals("")){
                    List<DeliveryRequestDetail> productInfoList = lodData.stream().filter(detailItem -> detailItem.getGuid().equals(item.getGuid())).collect(Collectors.toList());
                    if (productInfoList.size() != 0){
                        updateNum(deliveryRequest,productInfoList.get(0),params,1);
                    }
                    deliveryRequestDetailMapper.updateByGuid(item);
                } else {
                    item.setGuid(RandomValueUtils.getGUID());
                    //item.setCreateTime(new Date());
                    item.setpBid(deliveryRequest.getBid());
                    deliveryRequestDetailMapper.insertDeliveryRequestDetail(item);
                }
                //根据详情修改库存的减少可用数量
                updateNum(deliveryRequest,item,params,0);
            }

            for (DeliveryRequestDetail item : lodData
            ) {
                //是否删除
                List<DeliveryRequestDetail> productInfoList = onSonData.stream().filter(detailItem -> detailItem.getGuid().equals(item.getGuid())).collect(Collectors.toList());
                if (productInfoList.size() == 0){
                    deliveryRequestDetailMapper.delete(item);
                    updateNum(deliveryRequest,item,params,1);
                }
            }

        }
        
        if (!guidMap.isEmpty()){
            for (String guid : guidMap.keySet()){
                List<DeliveryRequestDetail> lodData = deliveryRequestDetailMapper.queryFirstByPBid(deliveryRequest.getBid());
                if (lodData.size()>0){
                    for (DeliveryRequestDetail item : lodData
                    ) {
                        //根据详情库存的回填可用数量
                        updateNum(deliveryRequest,item,params,1);
                    }
                }

                deliveryRequestDetailMapper.deleteByPBid(deliveryRequest.getBid());
                deliveryRequestMapper.delete(guid);
            }
        }



        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),resNid);
    }


    //修改可用数量
    private void updateNum(DeliveryRequest deliveryRequest,DeliveryRequestDetail item, Map<String,Object> params,Integer tpye){
        StockControl oldData ;
        StockControl stockControl = new StockControl();
        String operatorName = "";
        if (item.getGuidKc() != null && !item.getGuidKc().equals("")){
            Map<String, Object> params2 = new HashMap<String, Object>();
            params2.put("rkGuid",item.getRkGuid());
            params2.put("scGuid",item.getScGuid());
            params2.put("vGsBm",item.getvGsBm());
            params2.put("vHw",item.getCodeStockLocation());
            params2.put("vKq",item.getCodeStockArea());
            params2.put("gDepot",item.getCodeStockOn());
            params2.put("productcode",item.getCommodityCode());
            //oldData = stockControlMapper.findByMultiparameter(params2);
            oldData = deliveryRequestMapper.findByMultiparameterByDelivery(params2);
            if (oldData != null) {
                BeanUtils.copyProperties(oldData, stockControl);
                if (tpye == 0) {
                    operatorName = "修改";
                    if (oldData.getProductNum() < item.getNumDeliver()){
                        throw new RuntimeException("商品编码:"+item.getCommodityCode()+"库存数量不足,请核实后再操作!");
                    }
                    //可用数量-商品数量
                    stockControl.setProductNum(oldData.getProductNum() - item.getNumDeliver());
                } else {
                    operatorName = "删除";
                    //可用数量+商品数量
                    stockControl.setProductNum(oldData.getProductNum() + item.getNumDeliver());
                }
                stockControlMapper.update(stockControl);

                // 新库存添加库存流水
                StockControlRunning stockControlRunning = new StockControlRunning();
                stockControlRunning.setGuid(RandomValueUtils.getGUID());
                stockControlRunning.setGuidStockControl(stockControl.getGuid());
                stockControlRunning.setBidRelative(deliveryRequest.getBid());
                stockControlRunning.setLocationHw(item.getCodeStockLocation());
                stockControlRunning.setProductCode(item.getCommodityCode());
                stockControlRunning.setvGsBm(item.getvGsBm());
                stockControlRunning.setCreateTime(new Date());
                if (tpye == 0) {
                    stockControlRunning.setProductNumChange(-item.getNumDeliver());
                    stockControlRunning.setProductNumLeft(oldData.getProductNum() - item.getNumDeliver());
                    stockControlRunning.setRemark("新增海外仓发货申请单 - 调出方 " + deliveryRequest.getBid());
                } else {
                    stockControlRunning.setProductNumChange(item.getNumDeliver());
                    stockControlRunning.setProductNumLeft(oldData.getProductNum() + item.getNumDeliver());
                    stockControlRunning.setRemark("删除海外仓发货申请单 - 调入方 " + deliveryRequest.getBid());
                }

                stockControlRunningMapper.insert(stockControlRunning);
                updateLogService.addUpdateLog(params.get("moduleTable").toString(), stockControl.getGuid(), oldData, stockControl, operatorName);
            } else{
                throw new RuntimeException("商品编码:"+item.getCommodityCode()+"库存信息不存在,请核实后再操作!");
            }
        }
    }



    /**
     *@Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<DeliveryRequest> deliveryRequestList = deliveryRequestMapper.selectByNid(params);
        if (deliveryRequestList == null || deliveryRequestList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            infoMap.put("cid", deliveryRequestList.get(0).getCid());
            infoMap.put("bUser", deliveryRequestList.get(0).getbUser());
            infoMap.put("bDept", deliveryRequestList.get(0).getbDept());
            infoMap.put("procInstId", deliveryRequestList.get(0).getProcInstId());
            infoMap.put("activeFlow", deliveryRequestList.get(0).getActiveFlow());
            infoMap.put("createTime", deliveryRequestList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", deliveryRequestList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "go");
        }



        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (DeliveryRequest deliveryRequest : deliveryRequestList) {
            updateFlow.setGuid(deliveryRequest.getGuid().toString());
            updateFlow.setStateName(updateFlow.getActiveFlow().equals("end")?DeliveryRequestEnum.StateName.FLOW.value:DeliveryRequestEnum.StateName.INIT.value);
            deliveryRequestMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     *@Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<DeliveryRequest> deliveryRequestList = deliveryRequestMapper.selectByNid(params);
        if (deliveryRequestList == null || deliveryRequestList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            infoMap.put("cid", deliveryRequestList.get(0).getCid());
            infoMap.put("bUser", deliveryRequestList.get(0).getbUser());
            infoMap.put("bDept", deliveryRequestList.get(0).getbDept());
            infoMap.put("procInstId", deliveryRequestList.get(0).getProcInstId());
            infoMap.put("activeFlow", deliveryRequestList.get(0).getActiveFlow());
            infoMap.put("createTime", deliveryRequestList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", deliveryRequestList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (DeliveryRequest deliveryRequest : deliveryRequestList) {
            updateFlow.setGuid(deliveryRequest.getGuid().toString());
            updateFlow.setStateName(updateFlow.getActiveFlow().equals("end")?DeliveryRequestEnum.StateName.FLOW.value:DeliveryRequestEnum.StateName.INIT.value);
            deliveryRequestMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * 删除数据
     * @param
     * @return
     * @author DH-Xxj
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult delete(Map<String, Object> params) {
        List<DeliveryRequest> deliveryRequestList = JSON.parseArray(params.get("infoItems").toString(), DeliveryRequest.class);
        if (deliveryRequestList == null || deliveryRequestList.size() == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("数据异常!");
        }
        for (DeliveryRequest deliveryRequest : deliveryRequestList) {
            DeliveryRequest deliveryRequest1 = deliveryRequestMapper.queryFirstByGuid(deliveryRequest.getGuid());
            if (deliveryRequest1 == null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("海外仓申请计划不存在,请核实后在操作!");
            }

            List<DeliveryRequestDetail> lodData = deliveryRequestDetailMapper.queryFirstByPBid(deliveryRequest.getBid());
            if (lodData.size()>0){
                for (DeliveryRequestDetail item : lodData
                ) {
                    //根据详情库存的回填可用数量
                    updateNum(deliveryRequest,item,params,1);
                }
            }
            deliveryRequestDetailMapper.deleteByPBid(deliveryRequest.getBid());
            deliveryRequestMapper.delete(deliveryRequest.getGuid());

            String procInstId = deliveryRequest.getProcInstId();
            if (procInstId != null && !"".equals(procInstId)) {
                actProcessService.deleteProcess(procInstId);
                //插入指定单据流转各环节审批人记录（单据删除记录）
                Map<String, Object> flowRecord = new HashMap<String, Object>();
                flowRecord.put("moduleTable", moduleTable1);
                flowRecord.put("nid", deliveryRequest.getNid());
                flowRecord.put("activeFlowOld", "FlowZd");
                flowRecord.put("procInstId", procInstId);
                flowRecord.put("createUser", ShiroUtils.getMandatorId());
                flowRecord.put("createUserName", ShiroUtils.getMandatorName());
                flowRecord.put("updateUsers", "实际删除操作人： " + ShiroUtils.getUserName() + "【" + ShiroUtils.getUserId() + "】");
                flowRecord.put("optType", "delete");
                sysProcessInstanceMapper.insertProcessInstanceFlowRecord(flowRecord);
            }
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     *@Description: 查询前一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == ""){
            params.put("nid", "0");
        }
        params.put("stateName",DeliveryRequestEnum.StateName.SUCCESS.value);
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = deliveryRequestMapper.selectLastNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     *@Description: 查询后一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put("stateName",DeliveryRequestEnum.StateName.SUCCESS.value);
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = deliveryRequestMapper.selectNextNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }



    /**
     * 修改审核状态
     * @return
     * @author DH-Xxj
     * @throws Exception 
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateState(String bid) throws Exception {
    	
    	DeliveryRequest deliveryRequest = deliveryRequestMapper.findByBid(bid);
    	if (deliveryRequest.getEffectStock() != true) {
			return AjaxResult.error("流程尚未结束，无法审核下一步");
		} else if (deliveryRequest.getStateName().equals(DeliveryRequestEnum.StateName.SUCCESS.value)) {
			return AjaxResult.error("该单据已审核过，无法重复操作");
		}
    	
    	List<DeliveryRequestDetail> listDeliveryRequestDetail = deliveryRequestDetailMapper.queryFirstByPBid(bid);
    	
        String stateName = DeliveryRequestEnum.StateName.SUCCESS.value;
        deliveryRequestMapper.updateState(bid,  stateName);

        //新增装箱单
        DeliveryBox deliveryBox = new DeliveryBox();
        {

            Map<String, Object> params1 = new HashMap<String, Object>();
            params1.put("moduleTable", ModuleTable.DELIVERY_BOX);
            ModuleNidAndBid moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params1);    //有事务控制，制单异常不跳过单号

            deliveryBox.setGuid(RandomValueUtils.getGUID());
            deliveryBox.setBid(moduleNidAndBid.getBid());
            deliveryBox.setBidRequest(bid);
            deliveryBox.setNumAll(deliveryRequestDetailMapper.sumNumAll(bid));
            deliveryBox.setStateName(DeliveryBoxEnum.StateName.INIT.value);
            deliveryBoxMapper.insertDeliveryBox(deliveryBox);
        }
        
        List<Long> listGaugeMaintenanceId = new ArrayList<Long>();
        // 新增装箱单详情
        Integer boxNoCurrent = 1;
        for(DeliveryRequestDetail deliveryRequestDetail : listDeliveryRequestDetail) {
        	Long gaugeMaintenanceId = deliveryRequestDetail.getGaugeMaintenanceId();
        	if (listGaugeMaintenanceId.contains(gaugeMaintenanceId)) {
				continue;
			}
        	for (int i = 0; i < deliveryRequestDetail.getNumBox(); i++) {
        		
        		String productCode = deliveryRequestDetail.getCommodityCode();
        		ProductActive productActive = productActiveMapper.findProductActiveByCode(productCode);
        		
        		DeliveryBoxDetail deliveryBoxDetail = new DeliveryBoxDetail();
        		deliveryBoxDetail.setGuid(RandomValueUtils.getGUID());
        		deliveryBoxDetail.setBidBox(deliveryBox.getBid());
        		deliveryBoxDetail.setProductCode(deliveryRequestDetail.getCommodityCode());
        		deliveryBoxDetail.setProductName(deliveryRequestDetail.getName());
        		deliveryBoxDetail.setProductNameCn(productActive.getNameCn());
        		deliveryBoxDetail.setProductMaterialCn(productActive.getMaterialCn());
        		deliveryBoxDetail.setProductCodeHs(productActive.getCodeHs());
        		deliveryBoxDetail.setBoxNo(boxNoCurrent);
        		deliveryBoxDetail.setProductNum(deliveryRequestDetail.getNumSingleBox());
        		deliveryBoxDetail.setSizeLength(new BigDecimal(deliveryRequestDetail.getLength()));
        		deliveryBoxDetail.setSizeWidth(new BigDecimal(deliveryRequestDetail.getWidth()));
        		deliveryBoxDetail.setSizeHeight(new BigDecimal(deliveryRequestDetail.getHeight()));
        		deliveryBoxDetail.setSizeWeight(new BigDecimal(deliveryRequestDetail.getWeight()));
        		BigDecimal weightVol = deliveryBoxDetail.getSizeLength().multiply(deliveryBoxDetail.getSizeWidth()).multiply(deliveryBoxDetail.getSizeHeight()).divide(new BigDecimal(6000), 2, BigDecimal.ROUND_HALF_UP);
        		deliveryBoxDetail.setWeightVol(weightVol);
        		deliveryBoxDetail.setRemark("C3426-" + deliveryRequestDetail.getCommodityCode()); // 唛头格式：G3426-商品编码
        		deliveryBoxDetail.setStatus(1);
        		deliveryBoxDetailMapper.insertDeliveryBoxDetail(deliveryBoxDetail);
        		boxNoCurrent++;
			}
        	listGaugeMaintenanceId.add(gaugeMaintenanceId);
        }
        
//        // 添加转出流水
//        {
//            String vGsBm = "GS0641";
//            String vGsBmP = "GS0608";
//            BigDecimal fJe = new BigDecimal(0);
//            String vJyLx = "仓储服务→手续费";
//            String vBz = "海外仓发货，单号：" + deliveryRequest.getBid();
//            String mName = "仓储服务";
//            Integer mType = 1;
//            String mNid = deliveryRequest.getNid();
//            String mBid = deliveryRequest.getBid();
//            String mGuid = deliveryRequest.getGuid();
//            String operatorDept = deliveryRequest.getaDeptName();
//            String operatorPosition = deliveryRequest.getaPosition();
//            String operatorName = deliveryRequest.getaUserName();
//            String operatorUserId = deliveryRequest.getaUser();
//            accountDetailedForCompanyService.insertAccountDetailedForCompany(vGsBm, vGsBmP, fJe, vJyLx, vBz, mName, mType, mNid, mBid, mGuid, operatorDept, operatorPosition, operatorName, operatorUserId);
//        }
//        
//        // 添加转入流水
//        {
//            String vGsBm = "GS0608";
//            String vGsBmP = "GS0641";
//            BigDecimal fJe = new BigDecimal(0);
//            String vJyLx = "仓储服务→手续费";
//            String vBz = "海外仓发货，单号：" + deliveryRequest.getBid();
//            String mName = "仓储服务";
//            Integer mType = 1;
//            String mNid = deliveryRequest.getNid();
//            String mBid = deliveryRequest.getBid();
//            String mGuid = deliveryRequest.getGuid();
//            String operatorDept = deliveryRequest.getaDeptName();
//            String operatorPosition = deliveryRequest.getaPosition();
//            String operatorName = deliveryRequest.getaUserName();
//            String operatorUserId = deliveryRequest.getaUser();
//            accountDetailedForCompanyService.insertAccountDetailedForCompany(vGsBm, vGsBmP, fJe, vJyLx, vBz, mName, mType, mNid, mBid, mGuid, operatorDept, operatorPosition, operatorName, operatorUserId);
//        }
        
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }



}
